﻿using System;
using System.Configuration;
using System.Text;
using System.Data;
using System.Web;
using System.Collections;
using Newtonsoft.Json;
using System.Data.SqlClient;
using System.Collections.Generic;

namespace Common
{
	/// <summary>
	/// Assistant 的摘要说明。
	/// </summary>
    public sealed class Assiweb
    {
        public static DateTime miniDate = DateTime.Parse("1900-01-01");


        #region 四舍五入

        /// <summary>  
        /// 根据精度将金额转换为自定义类型的string  
        /// </summary>  
        /// <param name="precision">需要的精度</param>  
        /// <param name="money">需要转换的金额</param>  
        /// <returns>转换后的金额</returns>  
        public static string FormateString(decimal money, int precision = 2)
        {
            //比如，FormateString(2,2333)==>结果：2,333.00  
            string format = "###,###,###,##0.";
            for (int i = 0; i < precision; i++)
            {
                format = format + "0";
            }
            return money.ToString(format);
        }

        public static string FormateDate(DateTime dt, int kind = 2)
        {
            if (dt == miniDate) return "";
            string s =  dt.ToString("yyyy-MM-dd");
            if(s=="1900-01-01") return "";
            return s;
        }
            

        /// <summary>
        /// 从字符串里随机得到，规定个数的字符串.
        /// </summary>
        /// <param name="allChar"></param>
        /// <param name="CodeCount"></param>
        /// <returns></returns>
        private string GetRandomCode(string allChar, int CodeCount)
        {
            //string allChar = "1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,i,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z"; 
            string[] allCharArray = allChar.Split(',');
            string RandomCode = "";
            int temp = -1;
            Random rand = new Random();
            for (int i = 0; i < CodeCount; i++)
            {
                if (temp != -1)
                {
                    rand = new Random(temp * i * ((int)DateTime.Now.Ticks));
                }

                int t = rand.Next(allCharArray.Length - 1);

                while (temp == t)
                {
                    t = rand.Next(allCharArray.Length - 1);
                }

                temp = t;
                RandomCode += allCharArray[t];
            }
            return RandomCode;
        }

        /// <summary>
        /// 实现数据的四舍五入法
        /// </summary>
        /// <param name="v">要进行处理的数据</param>
        /// <param name="x">保留的小数位数</param>
        /// <returns>四舍五入后的结果</returns>
        public static double Round(double v, int x)
        {
            string s = "";
            if (x == 0)
            {
                s = "#0";
            }
            else if (x == 1)
            {
                s = "#0.0";
            }
            else if (x == 2)
            {
                s = "#0.00";
            }
            else if (x == 3)
            {
                s = "#0.000";
            }
            else if (x == 4)
            {
                s = "#0.0000";
            }
            s = v.ToString(s);
            v = Convert.ToDouble(s);
            return v;
        }

        public static decimal MyDecimalRound(decimal d)
        {
            d = d + 0.000000000000001m;
            return Decimal.Round(d, 2);
        }

        public static decimal MyDecimalRound(decimal d, int decimals)
        {
            d = d + 0.000000000000001m;
            return Decimal.Round(d, decimals);
        }

        #endregion

        #region 人民币大小写
        /// <summary> 
        /// 转换人民币大小金额 
        /// </summary> 
        /// <param name="num">金额</param> 
        /// <returns>返回大写形式</returns> 
        public static string CmycurD(decimal num)
        {
            string str1 = "零壹贰叁肆伍陆柒捌玖";            //0-9所对应的汉字 
            string str2 = "万仟佰拾亿仟佰拾万仟佰拾元角分"; //数字位所对应的汉字 
            string str3 = "";    //从原num值中取出的值 
            string str4 = "";    //数字的字符串形式 
            string str5 = "";  //人民币大写金额形式 
            int i;    //循环变量 
            int j;    //num的值乘以100的字符串长度 
            string ch1 = "";    //数字的汉语读法 
            string ch2 = "";    //数字位的汉字读法 
            int nzero = 0;  //用来计算连续的零值是几个 
            int temp;            //从原num值中取出的值 

            num = Math.Round(Math.Abs(num), 2);    //将num取绝对值并四舍五入取2位小数 
            str4 = ((long)(num * 100)).ToString();        //将num乘100并转换成字符串形式 
            j = str4.Length;      //找出最高位 
            if (j > 15) { return "溢出"; }
            str2 = str2.Substring(15 - j);   //取出对应位数的str2的值。如：200.55,j为5所以str2=佰拾元角分 

            //循环取出每一位需要转换的值 
            for (i = 0; i < j; i++)
            {
                str3 = str4.Substring(i, 1);          //取出需转换的某一位的值 
                temp = Convert.ToInt32(str3);      //转换为数字 
                if (i != (j - 3) && i != (j - 7) && i != (j - 11) && i != (j - 15))
                {
                    //当所取位数不为元、万、亿、万亿上的数字时 
                    if (str3 == "0")
                    {
                        ch1 = "";
                        ch2 = "";
                        nzero = nzero + 1;
                    }
                    else
                    {
                        if (str3 != "0" && nzero != 0)
                        {
                            ch1 = "零" + str1.Substring(temp * 1, 1);
                            ch2 = str2.Substring(i, 1);
                            nzero = 0;
                        }
                        else
                        {
                            ch1 = str1.Substring(temp * 1, 1);
                            ch2 = str2.Substring(i, 1);
                            nzero = 0;
                        }
                    }
                }
                else
                {
                    //该位是万亿，亿，万，元位等关键位 
                    if (str3 != "0" && nzero != 0)
                    {
                        ch1 = "零" + str1.Substring(temp * 1, 1);
                        ch2 = str2.Substring(i, 1);
                        nzero = 0;
                    }
                    else
                    {
                        if (str3 != "0" && nzero == 0)
                        {
                            ch1 = str1.Substring(temp * 1, 1);
                            ch2 = str2.Substring(i, 1);
                            nzero = 0;
                        }
                        else
                        {
                            if (str3 == "0" && nzero >= 3)
                            {
                                ch1 = "";
                                ch2 = "";
                                nzero = nzero + 1;
                            }
                            else
                            {
                                if (j >= 11)
                                {
                                    ch1 = "";
                                    nzero = nzero + 1;
                                }
                                else
                                {
                                    ch1 = "";
                                    ch2 = str2.Substring(i, 1);
                                    nzero = nzero + 1;
                                }
                            }
                        }
                    }
                }
                if (i == (j - 11) || i == (j - 3))
                {
                    //如果该位是亿位或元位，则必须写上 
                    ch2 = str2.Substring(i, 1);
                }
                str5 = str5 + ch1 + ch2;

                if (i == j - 1 && str3 == "0")
                {
                    //最后一位（分）为0时，加上“整” 
                    str5 = str5 + '整';
                }
            }
            if (num == 0)
            {
                str5 = "零元整";
            }
            return str5;
        }

        /**/
        /// <summary> 
        /// 一个重载，将字符串先转换成数字在调用CmycurD(decimal num) 
        /// </summary> 
        /// <param name="num">用户输入的金额，字符串形式未转成decimal</param> 
        /// <returns></returns> 
        public static string CmycurD(string numstr)
        {
            try
            {
                decimal num = Convert.ToDecimal(numstr);
                return CmycurD(num);
            }
            catch
            {
                return "非数字形式！";
            }
        }

        #endregion

        #region 文本转换为数值

        public static Int64 GetInt64(string val)
        {
            if (string.IsNullOrEmpty(val))
            {
                val = "0";
            }
            return Convert.ToInt64(val);
        }

        public static DateTime GetDatetime(string val)
        {
            if (string.IsNullOrEmpty(val))
            {
                val = "1900-01-01";
            }
            return Convert.ToDateTime(val);
        }

        public static int GetInt32(string val)
        {
            if (string.IsNullOrEmpty(val))
            {
                val = "0";
            }
            return Convert.ToInt32(val);
        }
        public static sbyte GetSByte(string val)
        {
            if (string.IsNullOrEmpty(val))
            {
                val = "0";
            }
            return Convert.ToSByte(val);
        }

        public static decimal GetDecimal(string val)
        {
            if (string.IsNullOrEmpty(val))
            {
                val = "0";
            }
            return Convert.ToDecimal(val);
        }

        #endregion

        #region 获取QueryString/Request上传的参数
        //public static string GetQueryString(string name) {
        //    string val = HttpContext.Current.Request.QueryString[name];
        //    if (!string.IsNullOrWhiteSpace(val))
        //    {
        //        val = val.Trim();
        //    }
        //    else {
        //        val = "";
        //    }
        //    return val;
        //}

        //public static Int64 GetQueryInt64(string name)
        //{
        //    return GetInt64(GetQueryString(name));
        //}

        //public static int GetQueryInt32(string name)
        //{
        //    string val = GetQueryString(name);
        //    if (val.Length == 0) { val = "0"; }
        //    return Convert.ToInt32(val);
        //}

        public static string GetRequestString(string name)
        {
            string val = "";
            try
            {
                val = HttpContext.Current.Request[name];



                if (string.IsNullOrWhiteSpace(val))
                {
                    val = "";
                }
                else
                {
                    val.Trim();
                }
            }
            catch (Exception ex)
            {
            }
            return val;
        }

        public static DateTime GetRequestDatetime(string name)
        {
            return Assiweb.GetDatetime(GetRequestString(name));
        }

        public static decimal GetRequestDecimal(string name)
        {
            return Assiweb.GetDecimal(GetRequestString(name));
        }

        //public static Int64 GetRequestInt64(string name)
        //{
        //    return GetInt64(GetRequestString(name));
        //}

        public static int GetRequestInt32(string name)
        {
            return Assiweb.GetInt32(GetRequestString(name));
        }

        //public static sbyte GetRequestSbyte(string name)
        //{
        //    return Convert.ToSByte(GetRequestString(name));
        //}

        public static bool StrIsEmpty(string val)
        {
            if (string.IsNullOrWhiteSpace(val))
            {
                return true;
            }
            return false;
        }

        public static bool StrIsNoEmpty(string val)
        {
            if (string.IsNullOrWhiteSpace(val))
            {
                return false;
            }
            return true;
        }

        public static bool IsNull(object val)
        {
            if (val == null || val == DBNull.Value)
            {
                return true;
            }
            return false;
        }

        public static bool DateIsNull(DateTime val)
        {
            if (val == null )
            {
                return true;
            }
            if (val == DateTime.MinValue) {
                return true;
            }
            if (val == miniDate) {
                return true;
            }
            return false;
        }

        public static bool NumIsNull(object val)
        {

            if (val == null)
            {
                return true;
            }
            decimal de = Convert.ToDecimal(val);
            if (de == 0) {
                return true;
            }
           
            return false;
        }

        #endregion

        #region 获取用户登录相关信息
        public static string GetUserID()
        {
            if (GetIsLocal())
            {
                return HttpContext.Current.Request.Cookies["UserGUID"].Value;
            }
            return HttpContext.Current.Session["UserGUID"].ToString();
        }

        public static string GetUserName()
        {
            if (GetIsLocal())
            {
                return HttpContext.Current.Request.Cookies["UserName"].Value;
            }
            return HttpContext.Current.Session["UserName"].ToString();
        }

        public static string GetUserCode()
        {
            if (GetIsLocal())
            {
                return HttpContext.Current.Request.Cookies["UserCode"].Value;
            }
            return HttpContext.Current.Session["UserCode"].ToString();
        }
        #endregion

        #region 获取相关快捷生成对象
        public static StringBuilder GetSB(string val = null)
        {
            StringBuilder sb = new StringBuilder();
            if (val != null && val.Length > 0)
            {
                sb.Append(val);
            }
            return sb;
        }

        public static string GetUrlEncode(string val)
        {
            return HttpUtility.UrlEncode(val);
        }

        public static DateTime GetSysDateTime()
        {
            //string sql = " select GETDATE() ";
            return DateTime.Now; //Convert.ToDateTime(SqlHelper.ExecuteScalar(sql));
        }

        public static Int64 GetSelfID()
        {
            string s = GetSysDateTime().ToString("yyMMddhhmmssfff");
            int t = (1000 + (new Random(Guid.NewGuid().GetHashCode())).Next(1, 1000)) - 1000;
            Int64 i6 = Convert.ToInt64(s) * 10000 + t;
            return i6;
        }
        

        /// <summary>
        /// 获取用户UA信息
        /// </summary>
        /// <param name="MobSystem">操作系统，2为安卓，3为iphone,ipod等苹果系列</param>
        /// <param name="IsUC">是否UC</param>
        /// <param name="http_UA">UA参数</param>
        /// <param name="http_WapPro">用户配置信息</param>
        public static void GetUAInfo(ref int MobSystem, ref bool IsUC, ref string http_UA, ref string http_WapPro)
        {
            int mobos = 0;            //操作系统版本
            int isuc = 0;                //是否UC
            string ALLUSERUA = "";    //用户UA
            string ALLWAPPRO = "";    //用户配置信息
            //获取UA
            if (HttpContext.Current.Request.ServerVariables["HTTP_USER_AGENT"] != null)
            {
                ALLUSERUA = HttpContext.Current.Request.ServerVariables["HTTP_USER_AGENT"].ToString().Trim();
            }
            //获取配置信息
            if (HttpContext.Current.Request.ServerVariables["HTTP_X_WAP_PROFILE"] != null)
            {
                ALLWAPPRO = "3G" + HttpContext.Current.Request.ServerVariables["HTTP_X_WAP_PROFILE"].ToString().Trim();
            }
            if (ALLUSERUA.IndexOf("UCWEB") > 0 || ALLWAPPRO.IndexOf("UCWEB") > 0 || ALLUSERUA.IndexOf("UCWEB") > 0 || ALLUSERUA.IndexOf(" UC ") > 0)
            {
                isuc = 1;
            }
            if (ALLUSERUA.IndexOf("QQBrowser") > 0 || ALLWAPPRO.IndexOf("QQBrowser") > 0 || ALLUSERUA.IndexOf("QQBrowser") > 0)
            {
                isuc = 1;
            }
            if (ALLUSERUA.IndexOf("Android") > 0 || ALLWAPPRO.IndexOf("Android") > 0 || ALLUSERUA.IndexOf("Ophone") > 0)
            {
                mobos = 2;
            }
            if (ALLUSERUA.IndexOf("UC") > 0 && ALLUSERUA.IndexOf("Linux") > 0)
            {
                mobos = 2;
            }
            if (ALLUSERUA.IndexOf("QQBrowser") > 0 && ALLUSERUA.IndexOf("Linux") > 0)
            {
                mobos = 2;
            }
            if (ALLUSERUA.IndexOf("iPhone") > 0 || ALLUSERUA.IndexOf("iPad") > 0 || ALLUSERUA.IndexOf("GT-I9000") > 0 || ALLUSERUA.IndexOf("IOS") > 0)
            {
                mobos = 3;
            }
            if (ALLUSERUA.IndexOf("UC") > 0 && ALLUSERUA.IndexOf("iOS") > 0)
            {
                mobos = 3;
            }
            if (ALLUSERUA.IndexOf("QQBrowser") > 0 && ALLUSERUA.IndexOf("iOS") > 0)
            {
                mobos = 3;
            }
            MobSystem = mobos;
            IsUC = (isuc == 1);
            http_UA = ALLUSERUA;
            http_WapPro = ALLWAPPRO;
        }



        public static Hashtable GetEiAjaxPost()
        {
            Hashtable ht = new Hashtable();
            int size = HttpContext.Current.Request.Form.AllKeys.Length;
            for (int i = 0; i < size; i++)
            {
                string name = HttpContext.Current.Request.Form.AllKeys[i];
                ht[name] = HttpContext.Current.Request.Form[name];
            }
            return ht;
        }


        

        public static bool GetIsLocal()
        {
            if (GetAppSettings("islocal") == "1")
            {
                return true;
            }
            return false;
        }
        public static string IsLocal = "";
        /// <summary>
        /// 获得配置文件appSettings子节点值
        /// </summary>
        /// <param name="key">键</param>
        /// <returns></returns>
        public static string GetAppSettings(string key)
        {
            if (IsLocal == "")
            {
                IsLocal = ConfigurationManager.AppSettings[key].ToString().Trim();
            }
            return IsLocal;
        }

        #endregion

        #region 获取Json相关转换
        public static object GetJsonObject(string val)
        {
            return new { success = false, re = val };
        }

        public static object GetJsonObject(string val, bool bl)
        {
            return new { success = bl, re = val };
        }

       

        public static string GetJsonDataTable(DataTable dt)
        {
            Newtonsoft.Json.Converters.IsoDateTimeConverter timeConverter = new Newtonsoft.Json.Converters.IsoDateTimeConverter();
            timeConverter.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
            string json = JsonConvert.SerializeObject(dt, Formatting.None, timeConverter); //把对象集合转换成Json
            return json;
        }

        public static string GetJsonStr(object ob) {
          string json =  JsonConvert.SerializeObject(ob);
          return json;
        }

        public static string GetJsonStr(bool bl)
        {
            string json = JsonConvert.SerializeObject(new { re = bl });
            return json;
        }

        public static string GetJsonStr(bool bl, string ex)
        {
            string json = GetJsonStr(new { re = bl, err = ex });
            return json;
        }

        public static string GetJsonStr(Exception ex)
        {
            string json = GetJsonStr(new { re = false, err = ex.Message + " - " + ex.StackTrace });
            return json;
        }

        #endregion

        #region 获取dataRow数据
        public static T GetDataRowCol<T>(DataRow dr, string name)
        {

            if (!dr.Table.Columns.Contains(name)) {
                return default(T);
            }
            
            if (dr[name] == DBNull.Value) return default(T);

            Type type = typeof(T);
            Object value;
            if (type == typeof(DateTime))
            {
                string s = dr[name].ToString().Trim();
                if (s.Length == 0)
                {
                    value = "1900-01-01";
                }
                else
                {
                    DateTime d = Convert.ToDateTime(s);
                    if (d == DateTime.MinValue) d = DateTime.Now;
                    value = d.ToString("yyyy-MM-dd HH:mm:ss");
                }
            }
            else if (type == typeof(Decimal))
            {
                string tmp = dr[name].ToString();
                if (StrIsEmpty(tmp)) { tmp = "0"; }
                Decimal d = Convert.ToDecimal(tmp);
                value = d.ToString();
            }
            else if (type == typeof(Int32))
            {
                string tmp = dr[name].ToString();
                if (StrIsEmpty(tmp)) { tmp = "0"; }
                int d = Convert.ToInt32(Convert.ToDecimal(tmp));
                value = d.ToString();
            }
            else { value = dr[name].ToString().Trim(); }
            return (T)Convert.ChangeType(value, typeof(T));
        }

        public static string GetDataRowCol_DataTime(DataRow dr, string name)
        {
            DateTime d;
            if (dr[name] == DBNull.Value)
            {
                d = DateTime.MinValue;
            }
            else
            {
                d = Convert.ToDateTime(dr[name]);
            }
            string value = d.ToString("yyyy-MM-dd HH:mm:ss");
            return value;
        }

        #endregion

        #region 获取用户权限相关

        
        public static bool GetUserAuth(DataRow[] adr, string rcode) {
            foreach (DataRow dr in adr) {
                if (dr["roce"].ToString().Trim() == rcode.Trim()) {
                    return true;
                }    
            }
            return false;
        }
        

        public static bool GetIsAdmin()
        {
            if (GetUserCode().ToLower() == "admin") {
                return true;
            }
            return false;
        }

        #endregion

        #region 数据字典
        public readonly static string Auth = "auth";
        public readonly static string AllAuth = "allauth";

        #endregion

        #region 上传下载及咋想
        public static string GetWeek()
        {
            string[] weekdays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
            string week = weekdays[Convert.ToInt32(DateTime.Now.DayOfWeek)];

            return week;
        }

        public static string GetWeek(DayOfWeek t)
        {
            string[] weekdays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
            string week = weekdays[Convert.ToInt32(t)];
            return week;
        }


        public static string GetDateStr(DateTime dt)
        {
            return dt.ToString("yyyy-MM-dd");
        }
        public static string GetDateStr(string sdt)
        {
            DateTime dt = Convert.ToDateTime(sdt);
            return dt.ToString("yyyy-MM-dd");
        }


        public static string DaoChu = "DaoChu";
        public static string DaoRu = "DaoRu";
        public static string GetDirectory(string name)
        {
            string folderPath = HttpContext.Current.Server.MapPath("~/" + name);
            if (!System.IO.Directory.Exists(folderPath))
            {
                System.IO.Directory.CreateDirectory(folderPath);
            }
            return folderPath;
        }
        #endregion

        #region 共用下拉列表
       
        #endregion

        public static int CalculateAgeCorrect(DateTime birthDate, DateTime now)
        {
            int age = now.Year - birthDate.Year;
            if (now.Month < birthDate.Month || (now.Month == birthDate.Month && now.Day < birthDate.Day)) age--;
            return age;
        }

        public static void GetSqlWhere(ref string where, string col, int type = 0)
        {
            string tmp = Assiweb.GetRequestString(col);
            if (Assiweb.StrIsNoEmpty(tmp))
            {
                if (type == 0)
                {
                    where += " and " + col + " like '%" + tmp + "%' ";
                }
                else if (type == 1)
                {
                    where += " and " + col + "=" + tmp + " ";
                }
                else if (type == 2)
                {
                    where += " and " + col + ">='" + tmp + "' ";
                }
                else if (type == 3)
                {
                    where += " and " + col + "<='" + tmp + "' ";
                }
            }

        }
    }
}
